package org.agilelang.plugin.load;

/*
 AgileLang - A fourth generation language(http://www.agilelang.org).

 Copyright (C) 2013 Roderick Cusirramos (roderick20@hotmail.com)

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;
import java.util.Vector;
import org.agilelang.plugin.IPlugin;
import org.agilelang.plugin.entities.Plugin;
import org.agilelang.plugin.manager.ManagerPlugin;

public class ManagerLoadPlugins {

    private static final String EXTENSION_JAR = ".jar";
    private static final String FOLDER_PLUGINS = "plugins";

    public static boolean loadPlugins(String path_xml) {
        boolean load = true;
        try {
            List<File> jars = searchPlugins(path_xml);
            ModifierClassPath cp = new ModifierClassPath();
            for (File jar : jars) {
                try {
                    cp.addArchivo(jar);
                } catch (MalformedURLException ex) {
                    System.err.println("URL incorrecta: " + ex.getMessage());
                }
            }
        } catch (Exception ex) {
            load = false;
            System.err.println(ex.getMessage());
        }
        return load;
    }

    private static List<File> searchPlugins(String path_xml) {
        List<File> files = new ArrayList<>();

        ManagerPlugin managerPlugin = new ManagerPlugin();
        managerPlugin.path_xml = path_xml;
        managerPlugin.read();

        for (Plugin plugin : managerPlugin.listPlugins.plugins) {
            files.add(new File(FOLDER_PLUGINS + File.separator + plugin.jar));

        }
        return files;
    }

    public static IPlugin[] getPlugins() {

        ServiceLoader<IPlugin> sl = ServiceLoader.load(IPlugin.class);
        sl.reload();

        Vector<IPlugin> vAv = new Vector<IPlugin>();

        for (Iterator<IPlugin> it = sl.iterator(); it.hasNext();) {
            try {
                IPlugin pl = it.next();
                vAv.add(pl);
            } catch (Exception ex) {
                System.err.println("Excepcion al obtener plugin: "
                        + ex.getMessage());
            }
        }

        return vAv.toArray(new IPlugin[0]);
    }
}
